﻿using MachineVision.API.Middlewares;
using MachineVision.API.Models;
using MachineVision.Service;
using MachineVision.Service.Dto;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System.Drawing.Printing;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace MachineVision.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MissionHistoryController : ControllerBase
    {
        private readonly ILogger<MissionHistoryController> logger;
        private readonly IMissionService mService;
        private readonly ITemperatureService _tService;
        private readonly IAppSettings settings;

        public MissionHistoryController(ILogger<MissionHistoryController> logger, IMissionService mService, IAppSettings settings)
        {
            this.logger = logger;
            this.mService = mService;
            this.settings = settings;
        }


        // GET: api/<MissionHistoryController>
        [HttpGet]
        public ApiResult Get(int pageNum = 1, int pageSize = 10, DateTime? TimeBegin = null, DateTime? TimeEnd = null)
        {
            ApiResult result = new ApiResult();
            result.data = mService.GetMissions(out int total,pageNum, pageSize, TimeBegin, TimeEnd);
            result.total = total;
            result.count = pageSize;
            result.page = pageNum;
            return result;
        }
        [Route("GetNums")]
        [HttpGet]
        public ApiResult GetNums(int pageNum = 1, int pageSize = 10, DateTime? TimeBegin = null, DateTime? TimeEnd = null)
        {
            ApiResult result = new ApiResult();
            result.data = mService.GetMissionNums(out int total, pageNum, pageSize, TimeBegin, TimeEnd);
            result.total = total;
            result.count = pageSize;
            result.page = pageNum;
            return result;
        }

        // GET api/<MissionHistoryController>/5
        [HttpGet("{id}")]
        public async Task<ApiResult> Get(int id)
        {
            return await Task.Run(() =>
            {
                ApiResult result = new ApiResult();
                result.data = mService.GetMission(id);
                return result;
            });
        }
        [Route("Get1Mission")]
        [HttpGet]
        public async Task<ApiResult> Get(string workNum, int pageNum = 1, int pageSize = 10)
        {
            return await Task.Run(() =>
            {
                ApiResult result = new ApiResult();
                result.data = mService.Get1Missions(workNum, out int total, pageNum, pageSize);
                result.total = total;
                result.count = pageSize;
                result.page = pageNum;
                return result;
            });
        }

        // POST api/<MissionHistoryController>
        [HttpPost]
        public ApiResult Post([FromBody] MissionHistory value)
        {
            ApiResult result = new ApiResult();
            result.data = mService.AddMission(value);
            if (value.WorkPlace != null && value.WorkPlace != 0)
            {
                _tService.AddData(new TemperatureReq { WorkPlace = value.WorkPlace, 
                    TemperatureC = decimal.TryParse(value.Temperature.ToString(), out decimal tmp) ? tmp : 0, 
                    Humidity = decimal.TryParse(value.Humidity.ToString(), out tmp) ? tmp : 0,
                    TempTime = DateTime.Now });
            } 
            else if (!string.IsNullOrEmpty(value.Terminal)&&_placeList.Contains(value.Terminal) && _workPlace != value.Terminal )
            {
                _workPlace = value.Terminal;
                if (value.WorkPlace == 0 || value.WorkPlace == null)
                {
                    value.WorkPlace = _placeList.IndexOf(value.Terminal);
                }
                _tService.AddData(new TemperatureReq { WorkPlace = value.WorkPlace, 
                    TemperatureC = decimal.TryParse(value.Temperature.ToString(), out decimal tmp) ? tmp : 0,
                    Humidity = decimal.TryParse(value.Humidity.ToString(), out tmp) ? tmp : 0,
                    TempTime = DateTime.Now });
            }
            return result;
        }
        string _workPlace = "";
        List<string> _placeList = new List<string>() {
            "LM29","LM37","LM14","LM50"
            //4 2 1 3 
        };

        [Route("GetExcel")]
        [HttpGet]
        public async Task<ActionResult> Get(string workNum)
        {
            //return await Task.Run(() =>
            {
                MissionNum num = mService.GetMissionNum(workNum);
                List<MissionHistory> data = mService.Get1Missions(workNum, out int total, 1, 999);

                var result = ExcelExtend.ToExcelFile(num,data);
                if (result.Success)
                {
                    var path= $"{Environment.CurrentDirectory+ result.PathStr}";//{settings.address}
                    return File(
                        new FileStream(path, FileMode.Open),
                        "application/octet-stream",
                        $"{num.Name}.xlsx"
                    //下边这种是返回下载连接,可通过浏览器直接访问下载   因为生成的excel文件保存在了程序根目录里的tempExcel文件夹里可直接返回网站路径   注意  如果以这种方式 一定要将存放excel的文件夹放在wwwroot下  也就是网站首页的文件夹
                    //return Json(new { ok = true, msg = "sucess", data = "http://********/tempExcel/"+ excelFilePath });
                    );

                }
                else {
                    return null;
                }
            }
            //);
        }
        

        // PUT api/<MissionHistoryController>/5
        //[HttpPut("{id}")]
        //public void Put(int id, [FromBody] string value)
        //{
        //}

        //// DELETE api/<MissionHistoryController>/5
        //[HttpDelete("{id}")]
        //public void Delete(int id)
        //{
        //}
    }
}
